package com.angel.bo.auth.server.service.impl;

import com.angel.bo.auth.client.jwt.AuthUtil;
import com.angel.bo.auth.server.constant.AuthServiceRestCode;
import com.angel.bo.auth.server.feign.UserService;
import com.angel.bo.auth.server.service.AuthService;
import com.angel.bo.beans.admin.entity.User;
import com.angel.bo.beans.jwt.JwtInfo;
import com.angel.bo.beans.jwt.JwtLogin;
import com.angel.bo.common.msg.WebReturn;
import com.angel.bo.common.util.ResultCheckUtil;
import com.xiaoleilu.hutool.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author: Haibo.Mei [Haibo.Mei@ge.com]
 * @Description:
 * @Date: 13:25 2018/1/30
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);

    @Autowired
    private UserService userService;

    @Autowired
    private AuthUtil authUtil;

    /**
     * @param jwtLogin
     * @Author: Haibo.Mei [Haibo.Mei@ge.com]
     * @Description:
     * @Date: 13:25 2018/1/30
     */
    @Override
    public WebReturn login(JwtLogin jwtLogin) {
        WebReturn<User> response =  userService.login(jwtLogin.getLoginName());
        log.info("login 返回状态码{}参数{}", response.getStatus(), response.getData());
        if(ResultCheckUtil.resultIsOk(response)){
            if(!ResultCheckUtil.resultHasData(response)){
                return new WebReturn<>(AuthServiceRestCode.USER_LOGIN_NO_USER);
            }
        }else{
            return response;
        }

        User user = BeanUtil.mapToBean((Map<?, ?>) response.getData(),User.class,false);
        if(!encoder.matches(jwtLogin.getPassWord(), user.getPassword())){
            return new WebReturn<>(AuthServiceRestCode.USER_LOGIN_PASS_ERROR);
        }

        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setUserId(user.getUserId()+"");
        jwtInfo.setLoginName(user.getLoginName());
        jwtInfo.setUserName(user.getUserName());
        String token = authUtil.generateToken(jwtInfo);
        response.setData(token);
        return response;
    }

    /**
     * @param token
     * @Author: Haibo.Mei [Haibo.Mei@ge.com]
     * @Description: 根据token获取用户信息
     * @Date: 13:44 2018/1/30
     */
    @Override
    public WebReturn<JwtInfo> getUserAllInfo(String token) {
        JwtInfo jwtInfo = null;
        try {
            jwtInfo = authUtil.getJwtFromToken(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new WebReturn<>(jwtInfo);
    }
}
